package com.aco.fatureapp;

import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aco.fatureapp.activity.AccessActivity;
import com.aco.fatureapp.activity.BaseActivity;
import com.aco.fatureapp.auxiliary.MenuAdapter;
import com.aco.fatureapp.fragments.MenuFragment;
import com.aco.fatureapp.model.ConfiguracaoApp;
import com.aco.fatureapp.model.Roteiro;
import com.aco.fatureapp.model.RoteiroConfig;
import com.aco.fatureapp.service.SrvImportRoute;
import com.aco.fatureapp.service.SrvMetering;
import com.aco.fatureapp.utilitary.CallAsyncTask;
import com.aco.fatureapp.utilitary.FileUtils;
import com.aco.fatureapp.utilitary.Utils;

/**
 * Main Control from Application.
 *
 * @author aldivone
 *
 */
@SuppressWarnings("deprecation")
@ContentView(R.layout.activity_home)
public class FatureHomeActivity extends BaseActivity {

	@InjectView(R.id.pnlHome)
	protected DrawerLayout mPnlHome;

	@InjectView(R.id.pnlHome_menu)
	protected ListView mLstMenu;

	@InjectView(R.id.pnlHome_view_home)
	protected LinearLayout mPnlDrawer;

	/*
	 * Info Menu Lateral
	 */
	@InjectView(R.id.name_user)
	private TextView mNameUser;

	@InjectView(R.id.num_version)
	private TextView mNumVersion;

	@InjectView(R.id.date_version)
	private TextView mDateVersion;

	private ActionBarDrawerToggle mActionBarDrawerToggle;

	private ConfiguracaoApp mConfigApp;

	private Roteiro mRoteiro;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Display button "home".
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		// Configure background home.
		mPnlHome.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

		// Configure menu home.
		configureMenuHome();

		// Configure actionBarDrawerToggle.
		configureActionBarDrawerToggle();

		// Show fragment home in first acess.
		if (savedInstanceState == null) {
			selectItem(0);
		}

		// registerAutoSync();

		infoLeituistaVersao();

		/*
		 * Checa a existência dos diretórios necessários para o correto
		 * funcionamento do aplicativo.
		 */
		FileUtils.checkDirectoryTree(FileUtils.DIRETORIO_DB_BACKUPS,
				FileUtils.DIRETORIO_IMG_BACKUPS, FileUtils.DIRETORIO_IMAGENS);
	}

	/**
	 * Registrar intervalo de tempo para a execução do envio automático.
	 *
	 */
	private void registerAutoSync() {
		try {
			mConfigApp = ConfiguracaoApp.findAll(ConfiguracaoApp.class).next();

			Integer tempoEmMinutos = mConfigApp.getTempoEnvio();

			if (tempoEmMinutos != null) {
				int tempoEmSegundos = tempoEmMinutos * 60;

				PendingIntent pIntent = PendingIntent.getBroadcast(
						FatureHomeActivity.this, 0, new Intent("IF_AUTO_SYNC"),
						0);

				AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);

				long intervalMillis = tempoEmSegundos * 1000;

				manager.setRepeating(AlarmManager.RTC_WAKEUP,
						System.currentTimeMillis() + intervalMillis,
						intervalMillis, pIntent);
			}
		}
		catch (Exception ex) {
			Log.e("IFATURE", ex.getMessage(), ex);
		}
	}

	/**
	 * Preencher as informações que serão exibidas no topo do menu lateral. Nome
	 * do leiturista logado, versão instalada do app e data da liberação da
	 * versão.
	 */
	private void infoLeituistaVersao() {
		try {
			if (usuarioLogado != null) {
				mNameUser.setText(usuarioLogado.getCodigo() + " - "
						+ usuarioLogado.getNome().split(" ")[0]);
			}

			mNumVersion
					.setText("Versão "
							+ getPackageManager().getPackageInfo(
									getPackageName(), 0).versionName);

			mDateVersion
					.setText("Atualizado em "
							+ getStringResourceByName(AccessActivity.DATE_BUILD_VERSION));
		}
		catch (final NameNotFoundException e) {
			mNumVersion.setText("");
		}
	}

	/**
	 * Configure home menu and register the click event.
	 */
	private void configureMenuHome() {
		mLstMenu.setAdapter(new MenuAdapter(this,
				R.layout.adapter_lateral_menu, Utils.getLstMenuItem()));

		/*
		 * Register the click event to home menu.
		 */
		mLstMenu.setOnItemClickListener(new OnItemClickListener() {

			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * android.widget.AdapterView.OnItemClickListener#onItemClick(android
			 * .widget.AdapterView, android.view.View, int, long)
			 */
			@Override
			public void onItemClick(final AdapterView<?> parent,
					final View view, final int positionMenuItem, final long id) {
				selectItem(positionMenuItem);
			}
		});
	}

	/**
	 * utes the design of the screen when you click the home button.
	 */

	private void configureActionBarDrawerToggle() {
		mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mPnlHome,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {

			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * android.support.v4.app.ActionBarDrawerToggle#onDrawerClosed(android
			 * .view.View)
			 */
			@Override
			public void onDrawerClosed(final View view) {
				mLstMenu.setItemChecked(0, true);
				getActionBar().setTitle(getTitle());
				invalidateOptionsMenu();
			}

			/*
			 * (non-Javadoc)
			 * 
			 * @see
			 * android.support.v4.app.ActionBarDrawerToggle#onDrawerOpened(android
			 * .view.View)
			 */
			@Override
			public void onDrawerOpened(final View drawerView) {
				getActionBar().setTitle("Menu");
				invalidateOptionsMenu();
			}
		};

		// Register actionBarDrawerToggle in home.
		mPnlHome.setDrawerListener(mActionBarDrawerToggle);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPostCreate(android.os.Bundle)
	 */
	@Override
	protected void onPostCreate(final Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		mActionBarDrawerToggle.syncState();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * roboguice.activity.RoboActivity#onConfigurationChanged(android.content
	 * .res.Configuration)
	 */
	@Override
	public void onConfigurationChanged(final Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		mActionBarDrawerToggle.onConfigurationChanged(newConfig);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {
		getMenuInflater().inflate(R.menu.action_bar_menu_home, menu);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(final MenuItem item) {
		if (mActionBarDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onMenuItemSelected(int, android.view.MenuItem)
	 */
	@Override
	public boolean onMenuItemSelected(final int featureId, final MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home: {
			if (!mPnlHome.isDrawerOpen(mPnlDrawer)) {
				mPnlHome.openDrawer(mPnlDrawer);
			}
			else {
				mPnlHome.closeDrawer(mPnlDrawer);
			}
			break;
		}
		case R.id.menu_sobre: {
			startActivity(new Intent("IF_ABOUT"));
			break;
		}
		case R.id.menu_backup: {
			Utils.alert(FatureHomeActivity.this, "Iniciar backup?",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(final DialogInterface dialog,
								final int which) {
							backup();
						}
					}, null);
			break;
		}
		case R.id.menu_restore: {
			Utils.alert(FatureHomeActivity.this, "Iniciar restore?",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(final DialogInterface dialog,
								final int which) {
							FileUtils.restore(FatureHomeActivity.this);
						}

					}, null);
			break;
		}
		case R.id.mnCleanBilling: {
			Utils.alert(
					FatureHomeActivity.this,
					"Confirmar a limpeza de todos os dados de faturamento? \n Todas as faturas são apagadas.",
					"Sim", "Não", new Dialog.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {

							new CallAsyncTask(FatureHomeActivity.this, true)
									.execute(new CallAsyncTask.Action() {

										@Override
										public String execute() {
											new SrvMetering()
													.deleteAllBilling();
											return null;
										}
									});
							dialog.dismiss();
						}
					}, new Dialog.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					}, false);
			return true;
		}
		case R.id.mnAjusteConfig: {

			SrvImportRoute srvImportRoute = new SrvImportRoute();
			RoteiroConfig config = srvImportRoute.getRoteiroConfig();

			if (config == null) {
				RoteiroConfig config2 = new RoteiroConfig();
				config2.setEncerrado(Boolean.FALSE);
				config2.setCargaLiberada(Boolean.FALSE);
				config2.setLeituraLiberada(Boolean.TRUE);
				config2.save();

				Toast.makeText(FatureHomeActivity.this,
						"Configuração restaurada com sucesso!",
						Toast.LENGTH_SHORT).show();
			}
			else {
				Toast.makeText(FatureHomeActivity.this,
						"Configuração está OK!", Toast.LENGTH_SHORT).show();
			}

			break;
		}

		case R.id.mnLiberarCarga: {

			SrvImportRoute srvImportRoute = new SrvImportRoute();
			RoteiroConfig config = srvImportRoute.getRoteiroConfig();

			if (config == null) {
				config = new RoteiroConfig();
			}

			config.setEncerrado(Boolean.TRUE);
			config.setCargaLiberada(Boolean.TRUE);
			config.setLeituraLiberada(Boolean.FALSE);
			config.save();

			Toast.makeText(FatureHomeActivity.this,
					"Carga liberada com sucesso!", Toast.LENGTH_SHORT).show();

			break;
		}
		}

		return true;
	}

	/**
	 * Execute action the selected option in home menu.
	 *
	 * @param position
	 *            selected option
	 */
	public void selectItem(final int position) {
		RoteiroConfig mRoteiroConfig = new SrvImportRoute().getRoteiroConfig();
		Fragment fragment = null;

		switch (position) {
		case 0:
			fragment = new MenuFragment();
			break;
		case 1:
			if (mRoteiro != null) {
				Intent intent = new Intent("IF_METERING");
				intent.putExtra(Roteiro.getTableName(Roteiro.class), mRoteiro);

				startActivity(intent);
			}
			else {
				Utils.alert(this,
						"Não há roteiro disponível, deseja importar agora?",
						new Dialog.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								startActivity(new Intent("IF_IMPORT"));
							}
						}, null);
			}

			break;
		case 2:
			startActivity(new Intent("IF_IMPORT"));
			break;
		case 3:
			if (mRoteiro != null && mRoteiroConfig != null
					&& !mRoteiroConfig.isEncerrado()) {
				Intent intent = new Intent("IF_EXPORT");
				intent.putExtra(Roteiro.getTableName(Roteiro.class), mRoteiro);

				startActivity(intent);
			}
			else {
				Utils.alert(
						this,
						"Não há roteiro disponível ou o mesmo está encerrado, deseja importar agora?",
						new Dialog.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								startActivity(new Intent("IF_IMPORT"));
							}
						}, null);
			}

			break;
		case 4:
			if (mRoteiro != null && mRoteiroConfig != null
					&& !mRoteiroConfig.isEncerrado()) {
				Intent intent = new Intent("IF_CLOSE_ROUTE");
				intent.putExtra(Roteiro.getTableName(Roteiro.class), mRoteiro);

				startActivity(intent);
			}
			else {
				Utils.alert(
						this,
						"Não há roteiro disponível ou o mesmo está encerrado, deseja importar agora?",
						new Dialog.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								startActivity(new Intent("IF_IMPORT"));
							}
						}, null);
			}

			break;
		case 5:
			startActivity(new Intent("IF_CONFIGURATION"));
			break;
		case 6:
			startActivity(new Intent("IF_PRINTER"));
			break;
		case 7:
			startActivity(new Intent("IF_REPORTS"));
			break;
		case 8:
			finish();
			break;
		default:
			break;
		}

		if (fragment != null) {
			final FragmentManager frgManager = getFragmentManager();

			frgManager.beginTransaction()
					.replace(R.id.pnlHome_frame_group, fragment).commit();

			mLstMenu.setItemChecked(position, true);
		}

		mPnlHome.closeDrawer(mPnlDrawer);
	}

	/**
	 * Executa o backup da base de dados.
	 */
	private void backup() {
		try {
			FileUtils.backup(FatureHomeActivity.this, null);

			Toast.makeText(this, "Backup realizado com sucesso!",
					Toast.LENGTH_SHORT).show();
		}
		catch (final Exception e) {
			Toast.makeText(this,
					"Falha no processo de backup da base de dados.",
					Toast.LENGTH_SHORT).show();
		}
	}

	public Roteiro getRoteiro() {
		return mRoteiro;
	}

	public void setRoteiro(Roteiro mRoteiro) {
		this.mRoteiro = mRoteiro;
	}
}